package models

import (
	"time"
)

type Role struct {
	ID        int       `json:"id"`
	Name      string    `json:"name"`
	Menus     []Menu    `json:"menus" gorm:"many2many:role_has_menu"`
	UpdatedAt time.Time `json:"updated_at"`
	CreatedAt time.Time `json:"created_at"`
}

func AddRole(name string, menuIds []int) error {
	role := Role{Name: name}
	if err := db.Create(&role).Error; err != nil {
		return err
	}

	var menus []Menu
	db.Where("id in (?)", menuIds).Find(&menus)
	if err = db.Model(&role).Association("Menus").Append(menus); err != nil {
		return err
	}

	return nil
}

func UpdateRole(id int, name string, menuIds []int) (err error) {
	var role Role
	if err = db.Where("id = ?", id).First(&role).Error; err != nil {
		return
	}

	if err = db.Model(&role).Update("name", name).Error; err != nil {
		return
	}

	if err = db.Model(&role).Association("Menus").Clear(); err != nil {
		return
	}

	var menus []Menu
	db.Where("id in (?)", menuIds).Find(&menus)
	if err = db.Model(&role).Association("Menus").Append(menus); err != nil {
		return
	}

	return nil
}

func GetRoles() (roles []Role, err error) {
	err = db.Preload("Menus").Find(&roles).Error

	return
}

func DelRole(id int) (err error) {
	var role Role
	if err = db.Where("id = ? ", id).First(&role).Error; err != nil {
		return
	}

	if err = db.Model(&Role{}).Association("Menus").Clear(); err != nil {
		return
	}

	if err = db.Delete(role).Error; err != nil {
		return
	}

	return
}
